package com.fingard.dsp.bank.directbank.gxnx02;

import java.sql.Connection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/10/10.
 */
public class GXNX02SinglePay extends GXNX02Base implements ISinglePay {

    private static final String INSERTRECEIPT = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,BUSITYPE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    private static final String SELECTRECEIPT = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? and BANKCODE=?;";

    /**
     * 单笔支付
     * @param p_req1908
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        return d_1908_SglPayB(p_req1908);
    }

    public RetAtsSingle d_1908_SglPayB(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        Connection conn = FGBiz.getLocalDbConn();
        try {
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            GXNX02Header header = new GXNX02Header();
            if("1".equals(p_req1908.singleDetail.sameBnk)){
                header.tranCode ="2001S";
            }else if("0".equals(p_req1908.singleDetail.sameBnk)){
                header.tranCode ="2002S";
            }
            header.tranSeq = Format.DateTime14Format.format(new Date())+bankFront.operator
                    +header.tranCode.substring(0,4)+getQryTransID();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            JDBCHelper.update(conn,INSERTRECEIPT,new Object[]{uuid,p_req1908.reqHeader.bankCode,header.tranCode,p_req1908.singleDetail.askNumber,header.tranSeq});
            writeCommonHeader1(xmlTextWriter,header);
            XElement body = new XElement("REQBODY","");
//            付款户名	M	GBString	140	PayAcctName
            body.addChild(new XElement("PayAcctName",p_req1908.singleDetail.payName));
//            付款帐号	M	NString	34	PayAcctNo
            body.addChild(new XElement("PayAcctNo",p_req1908.singleDetail.payAct));
            if("0".equals(p_req1908.singleDetail.sameBnk)){
                //收款行号	M	NString	32	RecBankNo
                body.addChild(new XElement("RecBankNo",p_req1908.singleDetail.cnapsCode));
                //收款行名	M	NString	140	RecBankName
                body.addChild(new XElement("RecBankName",p_req1908.singleDetail.cnapsName));
            }
//            收款户名	M	GBString	140	RecAcctName
            body.addChild(new XElement("RecAcctName",p_req1908.singleDetail.recName));
//            收款帐号	M	NString	34	RecAcctNo
            body.addChild(new XElement("RecAcctNo",p_req1908.singleDetail.recAct));
//            币种	M	NString	6	TranCcy CNY
            body.addChild(new XElement("TranCcy",convertCurToBank(p_req1908.singleDetail.payCur)));
//            金额	M	NString	16	TranAmt 交易发生金额
            body.addChild(new XElement("TranAmt",p_req1908.singleDetail.payAmount));
//            用途	O	GBString	40	Useage
            body.addChild(new XElement("Useage",p_req1908.singleDetail.purpose));
            nodeAnalysis(p_req1908.singleDetail.srcXElement,body,getCharset2());
            xmlTextWriter.writeXElement(body);
            xmlTextWriter.writeEndDocument();
            String[] bankResult = sendToBank1(xmlTextWriter.toXmlString());
            if(bankResult[0].length()==0){
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader xmlSbReader = loadBankRespXmlReader(bankResult[1],tmpSbMsg);
                if(xmlSbReader!=null){
                    String rspCode = xmlSbReader.getFirstText("/GXNXYQ/RESP/RESPHEAD/RspCode");
                    String rspMsg = xmlSbReader.getFirstText("/GXNXYQ/RESP/RESPHEAD/RspMsg");
                    detail.respCode ="0";
                    detail.respInfo = rspMsg;
                    detail.transState = rspCode;
                    detail.payInfoCode = detail.transState;
                    detail.reqSeqID = p_req1908.singleDetail.askNumber;
                }else {
                    detail.respCode ="-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            }else if (bankResult[0].equals(ConnState.FAIL)) {
                detail.respCode = "0";
                detail.respInfo = bankResult[1];
                detail.reqSeqID = p_req1908.singleDetail.askNumber;
                detail.transState = PaymentState.FAIL_Payment;
                detail.payInfoCode = bankResult[0];
            } else{
                detail.respCode ="-1";
                detail.respInfo = bankResult[1];
            }
        }catch (Exception e){
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            e.printStackTrace();
        }finally {
            conn.close();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }

    /**
     * 支付状态查询
     * @param p_req1944
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        return d_1944_QrySglPayB(p_req1944);
    }

    /**
     * 专线
     * @param p_req1944
     * @return
     * @throws Exception
     */
    public RetAtsSingle d_1944_QrySglPayB(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        Connection conn =FGBiz.getLocalDbConn();
        try{
            Map<String,Object> map = JDBCHelper.execQuerySingle(conn,SELECTRECEIPT,new Object[]{p_req1944.askNumber,p_req1944.reqHeader.bankCode});
            if(map.size()==0) {
                detail.respCode ="-1";
                detail.respInfo = "财务系统交易流水号关联映射异常，请检查";
                retAts.writeRetDetail(detail);
                return retAts;
            }
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            GXNX02Header header = new GXNX02Header();
            if("1".equals(p_req1944.sameBnk)){
                header.tranCode ="1005S";
            }else if("0".equals(p_req1944.sameBnk)){
                header.tranCode ="1006S";
            }
            header.tranSeq = Format.DateTime14Format.format(new Date())+bankFront.operator
                    +header.tranCode.substring(0,4)+getQryTransID();
            writeCommonHeader1(xmlTextWriter,header);
            xmlTextWriter.writeStartElement("REQBODY");
            xmlTextWriter.writeElementString("OriTranSeq",map.get("BANKREQSEQID").toString());
            xmlTextWriter.writeElementString("OriTranDate","",true);
            xmlTextWriter.writeElementString("OriTranCode","",true);
            xmlTextWriter.writeEndDocument();
            String[] bankResult = sendToBank1(xmlTextWriter.toXmlString());
            if (bankResult[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader xmlSbReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                if (xmlSbReader != null) {
                    String rspCode = xmlSbReader.getFirstText("/GXNXYQ/RESP/RESPHEAD/RspCode");
                    String rspMsg = xmlSbReader.getFirstText("/GXNXYQ/RESP/RESPHEAD/RspMsg");
                    if ("000000".equals(rspCode)) {
                        detail.respCode = "0";
                        detail.respInfo = xmlSbReader.getFirstText("/GXNXYQ/RESP/RESPBODY/TranMsg");
                        detail.reqSeqID = p_req1944.askNumber;
                        detail.transState = xmlSbReader.getFirstText("/GXNXYQ/RESP/RESPBODY/TranStatus");
                        detail.payInfoCode = detail.transState;
                    } else {
                        detail.respCode = "-1";
                        detail.respInfo = rspMsg;
                    }
                } else {
                    detail.respCode = "-1";
                    detail.respInfo = tmpSbMsg.toString();
                }
            } else {
                detail.respCode = "-1";
                detail.respInfo = bankResult[1];
            }
        }catch (Exception e){
            detail.respCode = "-1";
            detail.respInfo = e.getMessage();
            e.printStackTrace();
        }finally {
            conn.close();
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
